-module(db_homework).
-export([insert/4, add_answer/2, add_correction/2, add_rating/2, add_mark/2, get/1, delete/1, delete_all/0]).
-include("records.hrl").


% Insert a homework in the table
insert(Teacher, Student, Question, Difficulty) ->
	Date = {erlang:date(), erlang:time()},
	H = #homework {
		question = Question,
		difficulty = Difficulty,
		date = Date,
		teacher = Teacher,
		student = Student 
	},
	Fun = fun() ->
		Homework = case mnesia:last(homework) of
			'$end_of_table' ->
				H#homework{id = 0};
			LastId ->
				H#homework{id = LastId + 1}
		end,
		mnesia:write(Homework),
		Homework#homework.id
	end,
	mnesia:transaction(Fun).
	

% Update the homework Id adding the answer
add_answer(Id, Answer) ->
	Fun = fun() ->
		[H] = mnesia:read(homework, Id),
		HNew = H#homework{answer = Answer},
		mnesia:write(HNew)
	end,
	mnesia:transaction(Fun).
	
	
% Update the homework Id adding the correction
add_correction(Id, Correction) ->
	Fun = fun() ->
		[H] = mnesia:read(homework, Id),
		HNew = H#homework{correction = Correction},
		mnesia:write(HNew)
	end,
	mnesia:transaction(Fun).
	
	
% Update the homework Id adding the rating
add_rating(Id, Rating) ->
	Fun = fun() ->
		[H] = mnesia:read(homework, Id),
		HNew = H#homework{rating = Rating},
		mnesia:write(HNew)
	end,
	mnesia:transaction(Fun).
	
	
% Update the homework Id adding the mark
add_mark(Id, Mark) ->
	Fun = fun() ->
		[H] = mnesia:read(homework, Id),
		HNew = H#homework{mark = Mark},
		mnesia:write(HNew)
	end,
	mnesia:transaction(Fun).
	

% Get the homework with id ID
get(Id) ->
	Fun = fun() ->
		mnesia:read(homework, Id)
	end,
	mnesia:transaction(Fun).
	
	
% Delete a homework
delete(Id) ->
	Fun = fun() ->
		[H] = mnesia:read(homework, Id),
		mnesia:delete_object(H)
	end,
	mnesia:transaction(Fun).
	
% Delete all rows
delete_all() ->
	Fun = fun() ->
		Res = mnesia:select(homework, [{mnesia:table_info(homework, wild_pattern), [], ['$_']}]),
		lists:map(fun(X) -> mnesia:delete_object(X) end, Res)
	end,
	mnesia:transaction(Fun).
